<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader @add="addFn" :list="list" @isAll="isAll"></TodoHeader>
    <TodoMain :list="showList" @remove="removeFn" @change="changeFn"></TodoMain>
    <TodoFooter
      :list="list"
      @del="delFn"
      :type="type"
      @changeType="changeTypeFn"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import './styles/base.css'
import './styles/index.css'

import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list:JSON.parse(localStorage.getItem('todoList-homework')) || [],
      type: 'all',
    }
  },
  computed: {
    // 根据不同type值渲染界面
    showList() {
      if (this.type === 'no') {
        return this.list.filter((item) => !item.isDone)
      } else if (this.type === 'yes') {
        return this.list.filter((item) => item.isDone)
      } else {
        return this.list
      }
    },
  },
  methods: {
    // 删除元素
    removeFn(id) {
      // 筛选id不为删除项id的元素，并为list重新赋值
      this.list = this.list.filter((item) => item.id != id)
    },
    // 更改点击元素的isDone属性
    changeFn(id) {
      // 按照id找到list中对应的元素，并将它的isDone属性取反
      const obj = this.list.find((item) => item.id == id)
      obj.isDone = !obj.isDone
    },
    // 添加元素
    addFn(task) {
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 100,
        name: task,
        isDone: false,
      })
    },
    // 全选
    isAll(val) {
      this.list.forEach((item) => (item.isDone = val))
    },
    // 删除已完成
    delFn() {
      this.list = this.list.filter((item) => !item.isDone)
    },
    // 更改type值
    changeTypeFn(type) {
      this.type = type
    },
  },
  // 监听list，当list内容发生变化时更新至本地存储
  watch:{
    list:{
      deep: true,
      handler(){
        localStorage.setItem('todoList-homework', JSON.stringify(this.list))
      }
    }
  }
}
</script>
